#!/usr/bin/python2.4

"""Implement the bittorrent scrape GET request.

Originally part of the open-tracker project (http://code.google.com/p/open-tracker/),
modified to work with torrent-tracker.
"""

__author__ = 'allen@thebends.org (Allen Porter) and gavinandresen@gmail.com (Gavin Andresen)'

import os
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext import db

import model
import util
from BTL import bencode

class MainPage(webapp.RequestHandler):
  def __init__(self):
    self._files = { }

  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    info_hash = util.GetParam('info_hash')
    if len(info_hash) == 20:
      torrents = model.Torrent.gql("WHERE __key__ = KEY('Torrent', :1)",
                                info_hash.encode('hex_codec'))
    else:
      torrents = model.Torrent.gql("ORDER BY downloaded")
    for torrent in torrents:
      self.AddResult(torrent)
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write(bencode.bencode(self._files))

  def AddResult(self, torrent):
    self._files[torrent.key().name().decode('hex')] = {
        'complete' : 0,     # of seeders
        'downloaded' : 0,   # 'event=complete' seen
        'incomplete' : 0,   # leechers
        # Optional 'name' in the .torrent
      }

application = webapp.WSGIApplication(
    [ ( '/scrape', MainPage ) ],
    debug=True)

#os.environ['CONTENT_TYPE'] = "%s;charset=utf8" % os.environ['CONTENT_TYPE']
wsgiref.handlers.CGIHandler().run(application)
